package com.sxz.sbs.module.order;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.order.mode.IntentOrder;
import com.sxz.sbs.module.order.mode.OrderModifyStatusBean;
import com.sxz.sbs.module.order.presenter.OrderModifyPresenter;
import com.sxz.sbs.module.order.view.IOrderModifyView;
import com.sxz.sbs.module.photo.PhotoViewerActivity;
import com.sxz.sbs.module.photo.PhotoViewerBean;
import com.sxz.sbs.module.sale.mode.ImgBackBean;
import com.sxz.sbs.other.FileBean;
import com.sxz.sbs.other.ImageShowAdapter;
import com.sxz.sbs.util.StallUtil;
import com.sxz.sbs.view.SelfAdaptionGridView;
import com.sxz.sbs.widget.CommonTitle;
import com.sxz.sbs.widget.StallAlertDialog;
import com.tian.photopicker.PhotoPicker;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 订单修改
 *
 * @author tian
 * @date 2018/4/10
 */
public class OrderModifyActivity extends BaseActivity<OrderModifyPresenter> implements IOrderModifyView {


    @BindView(R.id.tv_order_modify_status)
    TextView tvOrderModifyStatus;
    @BindView(R.id.tv_order_modify_price)
    ClearEditText orderModifyPrice;
    @BindView(R.id.tv_order_modify_stages)
    TextView tvOrderModifyStages;
    @BindView(R.id.tv_order_modify_remarks)
    ClearEditText orderModifyRemarks;
    @BindView(R.id.order_modify_grid_view)
    SelfAdaptionGridView orderModifyGridView;
    @BindView(R.id.ll_modify_order_photo)
    LinearLayout llPhoto;
    @BindView(R.id.tv_photo_type_explain)
    TextView tvPhotoTypeExplain;
    private int statusInt;
    private OptionsPickerView stagesPicker, statusPicker;
    private List<FileBean> imgList;
    private ImageShowAdapter adapter;
    private List<OrderModifyStatusBean> statusData = new ArrayList<>();
    private IntentOrder intentOrder;
    private static final int SELECT_PHOTO_ALTER_ORDER = 1008;
    private ProgressDialog progressDialog;
    private  List<String> urlList = new ArrayList<>();
    private int deleteIndex;
    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("修改订单").build().show();
        Intent intent = getIntent();
        intentOrder = intent.getParcelableExtra("intent_order");
        if (intentOrder != null) {
            tvOrderModifyStages.setText(intentOrder.getIsByStage());
            orderModifyPrice.setText(intentOrder.getPrice());
            orderModifyRemarks.setText(intentOrder.getRemark());
            HashMap<String,Object> map = HttpParamMap.getParamMap();
            map.put("oldStatus",intentOrder.getStatusInt());
            mPresenter.getOrderOrderStatus(map);
            initStagesPicker();
            initGridView();
        }

    }



    /**
     * 初始化分期选择弹窗
     */
    private void initStagesPicker() {
        final List<String> stagesData = new ArrayList<>(2);
        stagesData.add("是");
        stagesData.add("否");
        stagesPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvOrderModifyStages.setText(stagesData.get(options1));
            }
        }).build();
        stagesPicker.setPicker(stagesData);
    }

    /**
     * 初始化图片列表
     */
    private void initGridView() {
        if (imgList == null) {
            imgList = new ArrayList<>();
        }
        adapter = new ImageShowAdapter(this,imgList,3);
        orderModifyGridView.setAdapter(adapter);
        adapter.setOnImageShowListener(new ImageShowAdapter.OnImageShowListener() {
            @Override
            public void onImageClick(View v, int position) {
                urlList.clear();
                for (int i = 0; i < imgList.size(); i++) {
                    if (imgList.get(i) != null) {
                        urlList.add(imgList.get(i).getPath());
                    }
                }
                PhotoViewerBean pvb = new PhotoViewerBean(urlList,position) ;
                startActivity(new Intent(OrderModifyActivity.this, PhotoViewerActivity.class)
                        .putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, pvb));
            }

            @Override
            public void onImageDelete(View v, int position) {
                deleteIndex = position;
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("fileId",imgList.get(position).getId());
                mPresenter.deletePhoto(map);
            }

            @Override
            public void onImageAdd(View v, int position) {
                PhotoPicker.builder().setSelectPhotoCount(3 - (imgList.size() - 1)).
                        start(OrderModifyActivity.this,SELECT_PHOTO_ALTER_ORDER);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_modify;
    }

    @Override
    protected OrderModifyPresenter createPresenter() {
        return new OrderModifyPresenter();
    }


    @OnClick({R.id.tv_order_modify_status, R.id.tv_order_modify_stages, R.id.btn_order_modify})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_order_modify_status:
                if (statusPicker != null) {
                    statusPicker.show();
                }
                break;
            case R.id.tv_order_modify_stages:
                hideKeyboard();
                if (stagesPicker != null) {
                    stagesPicker.show();
                }
                break;
            case R.id.btn_order_modify:
                if (TextUtils.isEmpty(tvOrderModifyStatus.getText().toString())) {
                    ToastUtils.showShort("请选择要修改的状态");
                    return;
                }
                if (TextUtils.isEmpty(orderModifyPrice.getInputValue())) {
                    ToastUtils.showShort("请填写订单总价");
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                if (statusInt == 6 || statusInt == 1) {
                    if (imgList.size() <= 1) {
                        ToastUtils.showShort("图片不能为空");
                        return;
                    }
                    for (int i = 0; i < imgList.size(); i++) {
                        if (imgList.get(i) != null && !TextUtils.isEmpty(imgList.get(i).getPath())) {
                            stringBuilder.append(imgList.get(i).getId()+",");
                        }
                    }
                }

                final String ids = StallUtil.cutToEndString(stringBuilder.toString());
                new StallAlertDialog.Builder(this)
                        .setMessage("确定修改此订单信息吗")
                        .setPositiveButton(new StallAlertDialog.OnPositiveListener() {
                            @Override
                            public void onPositiveClick(View view) {
                                HashMap<String,Object> map = new HashMap<>();
                                map.put("orderId",intentOrder.getOrderId());
                                map.put("status",statusInt);
                                map.put("dealPrice",orderModifyPrice.getInputValue());
                                map.put("isByStage","是".equals(tvOrderModifyStages.getText().toString())?1:0);
                                map.put("remarks",orderModifyRemarks.getInputValue());
                                map.put("photoId",ids);
                                mPresenter.modifyOrder(map);
                            }
                        }).create().show();
                break;
            default:
                break;
        }
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) tvOrderModifyStages.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(tvOrderModifyStages.getWindowToken(),0);
        }
    }

    @Override
    public void onGetOrderModifyStatus(List<OrderModifyStatusBean> data) {
        if (mIsLive && data != null) {
            statusData.addAll(data);
            initStatusPicker();
        }
    }

    @Override
    public void onUploadPhotoSuccess(List<ImgBackBean> mode) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (mIsLive && mode != null) {
            imgList.remove(imgList.size()-1);
            for (int i = 0; i < mode.size(); i++) {
                imgList.add(new FileBean(mode.get(i).getId(),mode.get(i).getPhotoUrl()));
            }
            adapter.setNotify(imgList);
        }
    }

    @Override
    public void onDeletePhotoSuccess() {
        imgList.remove(deleteIndex);
        adapter.setNotify(imgList);
    }

    @Override
    public void onModifyOrderSuccess() {
        finish();
    }

    /**
     * 初始化订单状态弹窗
     */
    private void initStatusPicker() {
        statusPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                OrderModifyStatusBean omsb = statusData.get(options1);
                tvOrderModifyStatus.setText(omsb.getName());
                statusInt = omsb.getValue();
                if (omsb.getValue() == 6) {
                    llPhoto.setVisibility(View.VISIBLE);
                    tvPhotoTypeExplain.setText("上传合同照片");
                } else if (omsb.getValue() == 1) {
                    llPhoto.setVisibility(View.VISIBLE);
                    tvPhotoTypeExplain.setText("上传定金凭证");
                } else if (omsb.getValue() == 2) {
                    llPhoto.setVisibility(View.VISIBLE);
                    tvPhotoTypeExplain.setText("上传退款流水图");
                } else {
                    llPhoto.setVisibility(View.GONE);

                }


            }
        }).build();
        statusPicker.setPicker(statusData);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
        progressDialog = ProgressDialog.show(this, null, "上传中...");
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            if (result.get(i) != null) {
                File newFile = new CompressHelper.Builder(this)
                        .setMaxWidth(720)
                        .setMaxHeight(1080)
                        .setQuality(60)
                        .setFileName(System.currentTimeMillis()+""+i)
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(new File(result.get(i)));
                if (newFile != null) {
                    fileList.add(newFile);
                }
            }
        }
        List<MultipartBody.Part> map = filesToMultipartBodyParts(fileList);
        mPresenter.uploadPhoto(0,map);
    }
    public  List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        int i = 1;
        for (File file : files) {
            i++;
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("fileList"+i, file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}
